package com.itheima.servlet;

import com.itheima.service.system.SyslogService;
import com.itheima.service.system.impl.SyslogServiceImpl;
import com.itheima.servlet.system.SyslogServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    private SyslogService ss = new SyslogServiceImpl();
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获取方法执行的初始时间
        long start = System.currentTimeMillis();
        //1、获取uri
        String uri = req.getRequestURI();
        //对uri进行判断:system/user/list
        //2、获取执行的方法名

        //执行方法
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        //url路径
        String url = uri.substring(0,uri.lastIndexOf("/"));
        //主机ip
        String remoteAddr = req.getRemoteAddr();
      /* req.setAttribute("url",url);
       req.setAttribute("methodName",methodName);
       req.setAttribute("remoteAddr",remoteAddr);*/
        try {
            //3、获取Method对象（反射）
            //3.1 方法名
            //3.2 参数列表：HttpServletRequest,HttpServletResponse
            //3.3 方法所在的对象:this
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //暴力反射
            method.setAccessible(true);
            //执行this对象上带有req和resp的method方法
            method.invoke(this,req,resp);
            //直接刷新会出现多一个/
            if(url.endsWith("/")){
              url =  url.substring(0,url.length()-1);
            }
            //不存操作日志的信息
            if(!url.equals("/pages/syslog")){
                ss.setLog(url,methodName,remoteAddr,start);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
